package serversidepkg;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import backendpkg.DataSource;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

/**
 * Servlet implementation class CheckIncoming
 */
public class CheckIncoming extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckIncoming() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			//Get username from session
			HttpSession session = request.getSession();			
            String user = (String) session.getAttribute("username");

            if (user == null) {
               request.setAttribute("Error", "Session has ended.  Please login.");
               RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
               rd.forward(request, response);
            }else{
			
	            response.setContentType("text/xml");
	            response.setHeader("Cache Control", "no-cache");
	            
	            //Get connection to database
	            DataSource datasource = new DataSource();
	            Connection conn = datasource.getConnection();
	            PreparedStatement statement;
	            
	            //Execute query in order to check if there are some incoming requests
	            String query = "SELECT * FROM Incoming WHERE receiver=? AND accepted='NULL'";
	            statement = (PreparedStatement) conn.prepareStatement(query);
	            statement.setString(1, user);
	            
	            ResultSet result = statement.executeQuery();          
	            
	            //Prepare xml string
	            String xml="<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?><root>";
	            
	            while(result.next()){
	                xml+="<requestor>" + result.getString("sender") + "</requestor>"; 
	            }
	            
	            xml+="</root>";
	            response.getWriter().write(xml);
            }
		} catch (SQLException e) {
		// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {            
        
		}
	}
}
